package study07;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Iterator;



public class ChatServer {
	  		//存放来自客户端的socket通信
			private HashSet<Socket>  clients = new HashSet<Socket>();
			//创造构造方法
			public ChatServer(){
						try {
							//建立服务端的端口号
							ServerSocket ss   =  new ServerSocket(8888);
							//建立连接
						   while (true) {
							//接受到客户端的通信流
							   Socket   s = ss.accept();
							 //通信信息加入到 集合中
							   clients.add(s);
							   //启动线程来单独处理收到的所有信息和单个通信
							   new ServerThread(s, clients).start();
						}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			}
			//使用内部类    也是一个线程，采用继承方式
			class   ServerThread  extends  Thread{
						private  Socket  s;
						private  HashSet  clients;
						public  ServerThread(Socket s,HashSet clients){
							this.s =s;
							this.clients = clients;
						}
						@Override
						public void run() {
						// TODO Auto-generated method stub
							//不停的接收又发送送消息给服务端
							try {
								BufferedReader  br = new BufferedReader(new InputStreamReader(s.getInputStream()));
								while (true) {
									sendMsg(br.readLine()+"\n");
									
								}
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
						}
						private  void  sendMsg(String str){
							//拿到所有的通信 不断的发会给客户端
							Iterator  it = clients.iterator();
							while (it.hasNext()) {
								Socket temp = (Socket) it.next();
								try {
									PrintWriter  printWriter  = new PrintWriter(temp.getOutputStream());
									printWriter.println(str);
									printWriter.flush();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
			}
			public static void main(String[] args) {
						new ChatServer();
			}
}
